# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
uuid    = require 'uuid'
secure  = require '../lib/secure'
router = express.Router()
module.exports = router

router.get '/', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "select * from pay_secure limit 1", defer err, result
    if err then done(client); return next(err)

    # 如果还没有配置，则自动生成默认配置
    if result.rows.length == 0
        await client.query \
            "insert into pay_secure (
                uuid, mpos_skey1, mpos_skey2, notes
            ) values ($1, $2, $3, $4)", [
                uuid.v4(), '', '', '默认配置'
            ], defer err, result
        if err then done(client); return next(err)
        done()
        res.redirect '/secure'
    else
        done()
        res.render 'secure', record: result.rows[0]


router.post '/edit', (req, res, next) ->
    for k in ['uuid', 'mpos_skey1', 'mpos_skey2']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    mpos_skey1 = secure.encryptEde req.body.mpos_skey1
    mpos_skey2 = secure.encryptEde req.body.mpos_skey2
    if not mpos_skey1 or not mpos_skey2
        return next new Error('加密母POS密钥分量错误，请检查...')

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "select * from pay_secure where uuid = $1", [
            req.body.uuid
        ], defer err, result
    if err then done(client); return next(err)
    if result.rows.length != 1
        done()
        return new Error('查询安全信息错误')

    old_record = result.rows[0]

    # 如果母 POS 密钥分量1 发生了变化，则重新加密存储
    if old_record.mpos_skey1 != req.body.mpos_skey1
        req.body.mpos_skey1 = secure.encryptEde req.body.mpos_skey1
        if not req.body.mpos_skey1
            done()
            return next new Error('加密母 POS 密钥分量1 错误，请检查...')

    # 如果母 POS 密钥分量2 发生了变化，则重新加密存储
    if old_record.mpos_skey2 != req.body.mpos_skey2
        req.body.mpos_skey2 = secure.encryptEde req.body.mpos_skey2
        if not req.body.mpos_skey2
            done()
            return next new Error('加密母 POS 密钥分量2 错误，请检查...')

    await client.query \
        "update pay_secure set
            mpos_skey1 = $1, mpos_skey2 = $2, notes = $3
        where uuid = $4", [
            req.body.mpos_skey1,
            req.body.mpos_skey2,
            req.body.notes,
            req.body.uuid
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.redirect '/secure'


router.post '/encrypt_ede', (req, res, next) ->
    res.type 'json'

    for k in ['key']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    if not req.session.userinfo.view_keys
        return next new Error("当前用户没有访问机密信息的权限")

    key = secure.encryptEde req.body.key
    return next new Error('加密失败，请查看日志') if not key

    return res.json succ: true, key: key


router.post '/decrypt_ede', (req, res, next) ->
    res.type 'json'

    for k in ['key']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    if not req.session.userinfo.view_keys
        return next new Error("当前用户没有访问机密信息的权限")

    key = secure.decryptEde req.body.key
    return next new Error('加密失败，请查看日志') if not key

    return res.json succ: true, key: key
